package com.zhang.chatcenter.service.chat.impl;

import com.alibaba.fastjson2.JSON;
import com.zhang.chatcenter.chat.ChannelHold;
import com.zhang.chatcenter.chat.ChatMessage;
import com.zhang.chatcenter.common.api.authority.UserRemote;
import com.zhang.chatcenter.common.model.dto.RoomMessageDTO;
import com.zhang.chatcenter.service.chat.IChatService;
import com.zhang.infrastructure.api.authority.UserRemoteVo;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2024-02-28 9:04
 **/
@RequiredArgsConstructor
@Slf4j
@Service
public class ChatService implements IChatService {

    private final UserRemote userRemote;

    /**
     * 如果是集群，需要采用广播模式发送给所有的服务器
     * */
    @Override
    public void send(ChatMessage chatMessage, List<Long> toList) {

        Map<Long, UserRemoteVo> userMap = userRemote.getUserByIds(Collections.singletonList(chatMessage.getUserId()));
        UserRemoteVo userRemoteVo = userMap.get(chatMessage.getUserId());
        String username = null;
        if(Objects.nonNull(userRemoteVo)){
            username = userRemoteVo.getUsername();
        }
        String finalUsername = username;
        ChannelHold.USER_CHANNEL.forEach((u, c)->{
            if(toList.contains(u)){
                RoomMessageDTO contentDTO = new RoomMessageDTO();
                contentDTO.setMessage(chatMessage.getMessage());
                contentDTO.setUserId(chatMessage.getUserId());
                contentDTO.setUsername(finalUsername);
                contentDTO.setRoomId(chatMessage.getRoomId());
                c.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(contentDTO)));
            }
        });
    }
}
